#define _CRT_SECURE_NO_WARNINGS 1
#include "Queue.h"

void QueueInit(Queue* q)
{	
	assert(q);
	q->phead = NULL;
	q->ptail = NULL;
	q->size = 0;
}

void QueuePush(Queue* q, QDataType x)
{
	assert(q);
	QNode* newcode = (QNode*)malloc(sizeof(QNode));
	if (newcode == NULL)
	{
		perror("malloc fail!\n");
		exit(1);
	}
	newcode->data = x;
	newcode->next = NULL;
	if (q->ptail == NULL)
	{
		q->phead = q->ptail = newcode;
	}
	else
	{
		q->ptail->next = newcode;
		q->ptail = newcode;
	}
	q->size++;
}

bool QueueEmpty(Queue* q)
{
	assert(q);
	return q->phead == NULL;
}

void QueuePop(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	if (q->phead == q->ptail)
	{
		free(q->phead);
		q->phead = q->ptail = NULL;
	}
	else
	{
		QNode* next = q->phead->next;
		free(q->phead);
		q->phead = next;
	}
	q->size--;
}

QDataType QueueFront(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	return q->phead->data;
}

QDataType QueueBack(Queue* q)
{
	assert(q);
	assert(!QueueEmpty(q));
	return q->ptail->data;
}

int QueueSize(Queue* q)
{
	assert(q);
	return q->size;
}

void QueueDestroy(Queue* q)
{
	assert(q);
	while (q->phead)
	{
		QNode* next = q->phead->next;
		free(q->phead);
		q->phead = next;
	}
	q->phead = q->ptail = NULL;
	q->size = 0;
}